<template>
    <div class="">
        <el-dialog title="平面图标记" :visible.sync="dialogVisible" width="80%" :before-close="closeDialog"
            :close-on-click-modal="false" :append-to-body="true">
            <div class="el_container">
                <div class="contLeft">
                    <div class="handle">
                        <div>
                            <el-button size="small" @click="onDeleteMark" icon="el-icon-delete"
                                type="primary">清空</el-button>
                            <el-button size="small" @click="onDel" icon="el-icon-delete" type="primary">删除设备</el-button>
                            <el-button size="small" @click="onEdit" icon="el-icon-edit-outline"
                                type="primary">更改平面图</el-button>
                        </div>
                        <div>
                            <el-button type="primary" icon="iconfont miaozhundingwei" size="small" style="height: 32px;"
                                @click="onrecover"></el-button>
                            <el-button type="primary" icon="el-icon-plus" size="small" @click="onlargen"></el-button>
                            <el-button type="primary" icon="el-icon-minus" size="small" @click="onlessen"></el-button>
                        </div>
                    </div>
                    <div class="container">
                        <div class="caritem_div">
                            <div class="div_box"
                                :style="{ transform: `scale(${scale}) `, left: `${x}px`, top: `${y}px` }"
                                @wheel="handleWheel" @mousedown.stop="handleMouseDown" @mousemove="handleMouseMove"
                                @mouseup="handleMouseUp">
                                <img class="elImage" :src="image" @click="setPoint" @mousedown.prevent />
                                <!-- @mousedown.stop="handleMouseDown2($event, item, index)"
                                @mousemove="handleMouseMove2($event, item, index)" @mouseup="handleMouseUp2"
                                @mousedown.prevent -->
                                <div class="device"
                                    :style="{ top: item.top + 'px', left: item.left + 'px', boxShadow: markId == item.id ? '0 0 15px rgba(115, 103, 240, 1)' : '' }"
                                    v-for="(item, index) in markVOList" :key="index">
                                    <img class="icon" :src="iconclass(item)" @click="clickTree(item)" />
                                    <div class="pop-up">
                                        <div style="margin-bottom: 5px">
                                            设备编码：{{ item.imei }}
                                        </div>
                                        <div style="margin-bottom: 5px">产品类型：{{ item.productName }}</div>
                                        <div >产品型号：{{ item.classMark }}</div>
                                        <!-- <div>安装备注：{{ item.remark || '-' }}</div> -->
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="el_aside">
                    <el-select v-model="productId" placeholder="产品类型" size="small" style="width: 100%" clearable
                        @visible-change="enterpriseChange" @change="getGetMark(false)">
                        <el-option v-for="item in productList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <el-select v-model="isMark" placeholder="标记" size="small" style="width: 100%;margin-top: 15px;"
                        clearable @change="getGetMark(false)">
                        <el-option v-for="item in isMarkList" :key="item.id" :label="item.name" :value="item.id">
                        </el-option>
                    </el-select>
                    <div class="dept-tree">
                        <div v-for="item in markList" :key="item.id"
                            :style="markId == item.id ? 'background-color: #7367F0;' : ''" @click="clickTree(item)">

                            <el-tooltip effect="dark" placement="left" :popper-class="'sub-poper-class'">
                                <div slot="content">设备编码：{{ item.imei }}<br />
                                    产品类型：{{ item.productName }}<br />
                                    产品型号：{{ item.classMark }}
                                    <!-- 安装备注：{{ item.remark || '-' }} -->
                                </div>
                                <div class="facility" :style="markId == item.id ? 'color:#fff;' : ''">
                                    <img :src="getimg(item.productName)" class="el_img" alt="">
                                    <span>{{ item.productName }}</span> <span style="font-size: 13px;color: #F12A2A;"><b
                                            v-if="item.mark == ''">未标记</b></span>
                                </div>
                            </el-tooltip>

                        </div>
                    </div>
                </div>

            </div>
          
        </el-dialog>

        <el-upload ref="upload" :show-file-list="false" :action="baseUrl" accept=".jpg,.png" :headers="headers"
            :before-upload="beforeAvatarUpload" :on-success="handleSuccessFunction">
            <i class="el-icon-plus"></i>
        </el-upload>
    </div>
</template>

<script>
import { reqProductList, reqGetMark, reqUpdateMark, reqDeleteMark, reqImageBatchUpdate } from "@api/api.js";
import asc from "@utils/asc.js"; //加密解密

export default {
    props: ["editInfo"],
    components: {},
    data() {
        return {
            dialogVisible: false,
            headers: {
                token: asc.decrypt(sessionStorage.getItem("token")),
            },
            productList: [],
            productId: "",
            isMark: '',
            isMarkList: [
                // {
                //     id:'1',
                //     name:'全部'
                // },
                {
                    id: '2',
                    name: '已标记'
                }, {
                    id: '3',
                    name: '未标记'
                },
            ],
            markId: '',
            markList: [],
            markVOList: [],
            left: 0,
            top: 0,
            flag: false,
            classIcon: "",

            // 放大缩小
            scale: 1, // 初始缩放比例为1
            scaleStep: 0.1, // 每次滚动缩放的步长

            // 鼠标拖动
            x: 0, // div的初始x坐标
            y: 0, // div的初始y坐标
            dragging: false, // 是否正在拖动
            startX: 0, // 鼠标按下时的x坐标
            startY: 0, // 鼠标按下时的y坐标

            dragging2: false, // 是否正在拖动
            startX2: 0, // 鼠标按下时的x坐标
            startY2: 0, // 鼠标按下时的y坐标

            itemInfo: {},
            image: "",
        };
    },
    computed: {},
    watch: {
        dialogVisible(e) {
            if (e) {
                this.$nextTick(async () => {
                    this.image = this.editInfo.image
                    await this.getProductList()
                    await this.getGetMark()
                })
            }
        }
    },
    methods: {
        // 上传文件之前的钩子
        beforeAvatarUpload(file) {
            let isJPG = true;
            let isLt = file.size / 1024 < 20000; // 判断是否小于500Kb
            if (file.type !== "image/png" && file.type !== "image/jpeg") {
                this.$modal.notifyWarning("图片只能是 jpg/png 格式!");
                isJPG = false;
                return isJPG;
            } else if (!isLt) {
                this.$modal.notifyWarning("图片大小不能超过20MB! 请重新上传");
                isJPG = false;
            }
            return isJPG;
        },
        // 上传成功
        async handleSuccessFunction(response, file, fileList) {
            // console.log(file);
            this.image = file.response.data.url;
            const res = await reqImageBatchUpdate({
                idList: [this.editInfo.id],
                image: this.image,
            });
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$modal.notifySuccess("图片上传成功");
        },
        onDeleteMark() {
            this.$confirm("确认清空平面图所有标记点吗？", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                    const res = await reqDeleteMark(this.editInfo.id)
                    if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
                    this.getGetMark()//设备刷新
                })
                .catch(() => { });
        },
        // 删除单个设备
        async onDel() {
            this.$notify.closeAll();
            if (this.markId == '') return this.$modal.notifyWarning('请选择要删除的设备');
            const res = await reqUpdateMark({
                id: this.markId,
                mark: ''
            })
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.markId = ''
            this.getGetMark()//未标记的设备刷新
        },
        onEdit() {
            this.$confirm("确认更换平面图吗?", "提示", {
                confirmButtonText: "确定",
                cancelButtonText: "取消",
                type: "warning",
            })
                .then(async () => {
                   // 手动触发文件选择对话框
                    this.$refs.upload.$el.querySelector('.el-upload__input').click();
                })
                .catch(() => { });
        },
        // 鼠标拖动
        // 用户按下鼠标按钮时触发
        handleMouseDown(event) {
            this.dragging = true;
            this.startX = event.clientX - this.x;
            this.startY = event.clientY - this.y;
        },
        // 用户移动鼠标时触发
        handleMouseMove(event) {
            if (!this.dragging) return;
            this.x = event.clientX - this.startX;
            this.y = event.clientY - this.startY;
        },
        // 用户释放鼠标按钮时触发
        handleMouseUp() {
            this.dragging = false;
        },
        // 用户按下鼠标按钮时触发
        handleMouseDown2(event, item, index) {
            // console.log(event.clientX, item);
            this.dragging2 = true;
            this.startX2 = event.clientX - this.markVOList[index].left;
            this.startY2 = event.clientY - this.markVOList[index].top;
        },
        // 用户移动鼠标时触发
        handleMouseMove2(event, item, index) {
            console.log(event, index);
            if (!this.dragging2) return;
            // this.markVOList[index].left = event.clientX - this.startX2;
            // this.markVOList[index].top = event.clientY - this.startY2;
            // 创建一个新的对象，包含更新后的属性
            const updatedItem = {
                ...this.markVOList[index], // 复制现有对象的所有属性
                left: event.clientX - this.startX2,
                top: event.clientY - this.startY2
            };
            // 使用 this.$set 来“更新”数组中的对象（实际上是替换它）
            this.$set(this.markVOList, index, updatedItem);
        },
        // 用户释放鼠标按钮时触发
        handleMouseUp2() {
            this.dragging2 = false;
        },
        onrecover() {
            this.scale = 1
            this.x = 0 // div的初始x坐标
            this.y = 0
        },
        onlargen() {
            this.scale += 0.3; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        onlessen() {
            this.scale -= 0.3; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        // 放大缩小
        handleWheel(event) {
            event.preventDefault(); // 阻止默认事件，防止页面滚动
            const delta = event.deltaY * -1; // 获取滚轮滚动的方向
            this.scale += delta > 0 ? this.scaleStep : -this.scaleStep; // 根据滚动方向调整缩放比例
            // 限制缩放比例的范围，防止过大或过小
            this.scale = Math.min(Math.max(0.1, this.scale), 5);
        },
        // 切换设备
        async clickTree(item) {
            // console.log(this.markId,item);
            if (this.markId == item.id) {
                // 点击相同设备
                this.markId = ''
                this.itemInfo = ''
                this.flag = false;
                return
            }
            this.itemInfo = item
            // 是否未标记
            if (item.mark == '') {
                this.flag = false;
            } else {
                this.flag = true;
            }
            this.markId = item.id
        },
        //绘制标记
        setPoint(e) {
            if (this.markId == '') return
            e = e || window.event;
            if (this.flag) {
                // 已标记
                // 实时更新其属性： 创建一个新的对象来替换旧的数组元素。这样 Vue 可以检测到数组的变化：
                const newMarkVOList = this.markVOList.map(item => {
                    if (item.id == this.markId) {
                        return {
                            ...item,
                            left: e.offsetX - 10 || e.layerX - 10,
                            top: e.offsetY - 17 || e.layerY - 17
                        };
                    }
                    return item;
                });
                this.markVOList = newMarkVOList;
            } else {
                // 未标记
                this.itemInfo.left = e.offsetX - 10 || e.layerX - 10;
                this.itemInfo.top = e.offsetY - 17 || e.layerY - 17;
                this.markVOList.push(this.itemInfo)
            }
            this.flag = true;//未标记变成已标记
            this.left = e.offsetX - 10 || e.layerX - 10;
            this.top = e.offsetY - 17 || e.layerY - 17;
            this.submit() // 修改标记
        },
        // 修改标记
        async submit() {
            // if (!this.flag) return;
            const res = await reqUpdateMark({
                id: this.markId,
                mark: this.left + "," + this.top
            })
            // console.log(res);
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.$notify.closeAll();
            this.$modal.notifySuccess("修改标记成功");
            this.getGetMark(true)//未标记的设备刷新
        },
        // 标记点图片
        iconclass(e) {
            // console.log(e);
            // if (e.isAlarm == 1) {
            //     return "hon";
            // }
            // if (e.online == 0) {
            //     return "lixian";
            // }
            let pic = ''
            this.productList.forEach(item => {
                if (item.name == e.productName) {
                    pic = item.pic
                }
            })
            return pic
        },
        //获取平面图设备标点
        async getGetMark() {
            const res = await reqGetMark(1,99,{
                floorId: this.editInfo.id,
                isMark: this.isMark,
                productId: this.productId
            })
            this.markVOList = res.data.row.markVOList || [];//平面图点位
            this.markList = res.data.row.markVOList || []//设备列表
            if (this.markVOList.length == 0) return;
            this.markVOList = this.markVOList.filter((item) => item.mark != "");
            this.markVOList.forEach((item) => {
                item.left = item.mark.slice(0, item.mark.indexOf(","));
                item.top = item.mark.slice(item.mark.indexOf(",") + 1);
            });
        },


        // 下拉请求列表
        enterpriseChange(val) {
            if (val) {
                this.getProductList();
            }
        },
        //   获取产品列表
        async getProductList() {
            const res = await reqProductList();
            if (res.code !== 20000) return this.$modal.notifyWarning(res.message);
            this.productList = res.data.rows;
        },
        getimg(productName) {
            let pic = ''
            this.productList.forEach(item => {
                if (item.name == productName) {
                    pic = item.pic
                }
            })
            return pic
        },

        // 点击关闭弹框
        closeDialog() {
            // this.$parent.getImagePage()
            this.dialogVisible = false;
            this.markList = [];
            this.markId = '';
            this.flag = false;
            this.productId = ''
            this.isMark = ''
            this.scale = 1 // 初始缩放比例为1
            this.scaleStep = 0.1 // 每次滚动缩放的步长
            this.x = 0// div的初始x坐标
            this.y = 0 // div的初始y坐标
            this.dragging = false // 是否正在拖动
            this.startX = 0 // 鼠标按下时的x坐标
            this.startY = 0 // 鼠标按下时的y坐标
        },
    },
    created() {
        this.baseUrl = `${this.$baseURL_copy}file/upload`;
    },
    mounted() { },
};
</script>
<style lang="less">
.sub-poper-class {
    background: #7367F0 !important;
    font-size: 14px;
    line-height: 25px;
}

.sub-poper-class .popper__arrow::after {
    border-left-color: #7367F0 !important;
    /* 修改为你想要的颜色 */
}
</style>

<style lang="less" scoped>
@import url("~@views/common.less");

::v-deep .el-dialog {
    height: 100%;
}

::v-deep .el-dialog__body {
    padding: 20px;
}

.el_container {
    display: flex;
    height: 100%;
    width: 100%;
    box-sizing: border-box;

    .el_aside {
        width: 320px;
        margin-left: 20px;
        padding: 13px;
        box-sizing: border-box;
        // background-color: @primaryBgcolor7;
        border: 1px solid @primaryBorderColor;

        .dept-tree {
            margin-top: 10px;
            height: 82%;
            // overflow: auto;
            overflow-y: clip;
            padding: 0 1px;

            .facility {
                display: flex;
                align-items: center;
                // height: 32px;
                padding: 8px 5px;
                cursor: pointer;
                color: @primaryThemeTxtColor;
                border-radius: 4px;
                position: relative;

                >span:first-of-type {
                    width: 63%;
                }

                >span:last-of-type {
                    flex: 1;
                    text-align: center;
                }
            }

            >div {
                &:hover {
                    background: @primaryBorderColor7;
                }
            }

            .pop-upu {
                position: absolute;
                // left: 10px;
                bottom: 28px;
                left: -20%;
                transform: translate(-50%, 0);
                background: rgba(115, 103, 240, 0.9);
                width: 250px;
                padding: 8px 10px;
                border-radius: 5px;
                font-size: 14px;
                color: #fff;
                z-index: 9999;
                // user-select:none;
                opacity: 0;
                visibility: hidden;
                transition: all 0.2s ease-in;
                cursor: text;
                opacity: 1;
                visibility: visible;

                &:after {
                    content: "";
                    border: solid transparent;
                    border-width: 8px 8px 0 0;
                    /* 上边框和下边框透明，左边框宽度为箭头大小，右边框为0 */
                    border-left-color: rgba(115, 103, 240, 0.9);
                    /* 设置左边框的颜色 */
                    position: absolute;
                    top: 50%;
                    right: -8px;
                    /* 根据边框宽度调整，确保箭头在元素外部 */
                    transform: translateY(-50%);
                    /* 垂直居中 */
                    margin-left: 0;
                    /* 确保没有额外的水平偏移 */
                }
            }

            .el_img {
                width: 36px;
                height: 36px;
                border-radius: 50%;
                margin-right: 16px;
            }
        }
    }

    .contLeft {
        flex: 1;
        display: flex;
        flex-direction: column;

        .handle {
            margin-bottom: 15px;
            display: flex;
            justify-content: space-between;

            >div {
                display: flex;
                align-items: center;
            }

            ::v-deep .miaozhundingwei {
                font-size: 14px !important;
            }
        }
    }

    .container {
        flex: 1;
        height: 100%;
        overflow: hidden;
        display: flex;
        align-items: center;
        justify-content: center;
        border: 1px solid @primaryBorderColor;

        // background-color: @primaryBgcolor7;
        .caritem_div {
            width: 800px;
            height: 450px;
            position: relative;
        }

        .div_box {
            width: 800px;
            height: 450px;
            position: absolute;
            top: 50%;
            left: 50%;
            // transform: translate(-50%, -50%);

            .elImage {
                cursor: pointer;
                width: 100%;
                height: 100%;
            }

            .device {
                position: absolute;
                width: 34px;
                height: 34px;
                border-radius: 50%;

                .pop-up {
                    position: absolute;
                    // left: 10px;
                    bottom: 50px;
                    left: 50%;
                    transform: translate(-50%, 0);
                    background: rgba(115, 103, 240, 0.9);
                    width: 250px;
                    padding: 8px 10px;
                    border-radius: 5px;
                    font-size: 14px;
                    color: #fff;
                    z-index: 9999;
                    // user-select:none;
                    opacity: 0;
                    visibility: hidden;
                    transition: all 0.2s ease-in;
                    cursor: text;

                    &:after {
                        content: "";
                        border: 8px solid transparent;
                        border-top-color: rgba(115, 103, 240, 0.9);
                        position: absolute;
                        bottom: -15px;
                        left: 50%;
                        transform: translate(-50%, 0);
                    }
                }

                &:hover .pop-up {
                    opacity: 1;
                    visibility: visible;
                }
            }

            .icon {
                position: absolute;
                // color: #28c76f;
                border-radius: 50%;
                font-size: 18px;
                width: 34px;
                height: 34px;
            }

            .hon {
                color: #F84242;
            }

            .lixian {
                color: #90A4AE;
            }
        }
    }
}
</style>
